<template>
  <div class="claim-list-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>农业保险查勘任务列表</h1>
    </div>

    <!-- 搜索筛选区域（仅保留报案号查询） -->
    <div class="search-container">
      <el-row :gutter="24" class="mb-4">
        <!-- 报案号搜索（后端参数为reportId，与页面展示的“报案号”对应） -->
        <el-col :span="10">
          <el-input v-model="searchForm.reportId" placeholder="请输入报案号（如REP2023091900001）" prefix-icon="Search" clearable
            @keyup.enter="handleSearch" />
        </el-col>
        <!-- 搜索/重置按钮 -->
        <el-col :span="6" class="btn-group">
          <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
          <el-button type="default" icon="RefreshLeft" @click="resetSearch" class="ml-2">重置</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 查勘任务列表表格（按后端返回字段展示） -->
    <el-table :data="claimList" border stripe :loading="tableLoading" style="width: 100%"
      :header-cell-style="{ background: '#f8f9fa', fontWeight: '500' }" empty-text="暂无匹配的查勘任务记录"
      :row-key="row => row.surveyId">
      <!-- 序号 -->
      <el-table-column label="序号" type="index" align="center" min-width="60">
        <template #default="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>

      <!-- 查勘ID（后端返回：surveyId） -->
      <el-table-column prop="surveyId" label="查勘ID" align="center" min-width="100" />

      <!-- 调度ID（后端返回：dispatchId） -->
      <el-table-column prop="dispatchId" label="调度ID" align="center" min-width="100" />

      <!-- 报案号（后端返回：reportNo，对应搜索参数reportId） -->
      <el-table-column prop="reportNo" label="报案号" align="center" min-width="180" />

      <!-- 保单号（后端返回：policyId） -->
      <el-table-column prop="policyId" label="保单号" align="center" min-width="140" />

      <!-- 查勘员工号（后端返回：surveyorWorkNo） -->
      <el-table-column prop="surveyorWorkNo" label="查勘员工号" align="center" min-width="140">
        <template #default="scope">
          <span>{{ scope.row.surveyorWorkNo || '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="surveyStatus" label="查勘状态" align="center" min-width="120">
        <template #default="scope">
          <el-tag :type="getSurveyStatusTagType(scope.row.surveyStatus)" size="small">
            {{ getSurveyStatusText(scope.row.surveyStatus) }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 查勘地点（后端返回：surveyAddress） -->
      <el-table-column prop="surveyAddress" label="查勘地点" align="center" min-width="280">
        <template #default="scope">
          <el-tooltip :content="scope.row.surveyAddress" placement="top" effect="dark"
            :disabled="scope.row.surveyAddress?.length <= 30">
            <span class="location-text">
              {{ scope.row.surveyAddress?.length > 30
                ? scope.row.surveyAddress.slice(0, 30) + '...'
                : scope.row.surveyAddress || '--'
              }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>

      <!-- 调度备注（后端返回：dispatchRemark） -->
      <el-table-column prop="dispatchRemark" label="调度备注" align="center" min-width="200">
        <template #default="scope">
          <el-tooltip :content="scope.row.dispatchRemark" placement="top" effect="dark"
            :disabled="scope.row.dispatchRemark?.length <= 20">
            <span>{{ scope.row.dispatchRemark?.length > 20
              ? scope.row.dispatchRemark.slice(0, 20) + '...'
              : scope.row.dispatchRemark || '--'
            }}</span>
          </el-tooltip>
        </template>
      </el-table-column>

      <!-- 查勘员确认时间（后端返回：surveyorConfirmTime） -->
      <el-table-column prop="surveyorConfirmTime" label="查勘员确认时间" align="center" min-width="300">
        <template #default="scope">
          {{ formatDateTime(scope.row.surveyorConfirmTime) || '--' }}
        </template>
      </el-table-column>

      <!-- 报案人姓名（后端返回：reporterName） -->
      <el-table-column prop="reporterName" label="报案人姓名" align="center" min-width="120" />

      <!-- 报案人电话（后端返回：reporterPhone） -->
      <el-table-column prop="reporterPhone" label="报案人电话" align="center" min-width="140" />

      <!-- 操作列 -->
      <el-table-column label="操作" align="center" min-width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" icon="Eye" @click="openDetailDialog(scope.row)" class="mr-2">
            详情
          </el-button>
          <el-button type="success" size="small" icon="Edit" @click="toHandlePage(scope.row)">
            处理
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container" v-if="total > 0 && !tableLoading">
      <el-pagination @size-change="handlePageSizeChange" @current-change="handleCurrentPageChange"
        :current-page="currentPage" :page-sizes="[2, 5, 10, 20]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" background />
    </div>

    <!-- 空数据/加载失败提示 -->
    <div class="empty-container" v-else-if="!tableLoading">
      <el-empty :description="errorMsg || '暂无查勘任务记录，请调整搜索条件后重试'" image-size="100" />
      <el-button type="text" class="mt-4" @click="fetchData" v-if="errorMsg">
        重新加载
      </el-button>
    </div>

    <!-- 详情弹窗（按后端字段调整展示） -->
    <el-dialog title="查勘任务详情" v-model="detailDialogVisible" width="70%" destroy-on-close>
      <el-form :model="currentDetailData" label-width="180px" class="detail-form" size="medium">
        <el-row :gutter="20">
          <!-- 基础信息 -->
          <el-col :span="12">
            <el-form-item label="查勘ID">
              <el-input :value="currentDetailData.surveyId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调度ID">
              <el-input :value="currentDetailData.dispatchId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报案号">
              <el-input :value="currentDetailData.reportNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保单号">
              <el-input :value="currentDetailData.policyId" disabled />
            </el-form-item>
          </el-col>

          <!-- 查勘人员信息 -->
          <el-col :span="12">
            <el-form-item label="查勘员工号">
              <el-input :value="currentDetailData.surveyorWorkNo || '--'" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="查勘状态">
              <el-tag :type="getSurveyStatusTagType(currentDetailData.surveyStatus)" size="small">
                {{ getSurveyStatusText(currentDetailData.surveyStatus) }}
              </el-tag>
            </el-form-item>
          </el-col>

          <!-- 其他信息 -->
          <el-col :span="24">
            <el-form-item label="查勘地点">
              <el-input :value="currentDetailData.surveyAddress || '--'" disabled rows="2" type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="调度备注">
              <el-input :value="currentDetailData.dispatchRemark || '--'" disabled rows="2" type="textarea" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="查勘员确认时间">
              <el-input :value="formatDateTime(currentDetailData.surveyorConfirmTime) || '--'" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报案人姓名">
              <el-input :value="currentDetailData.reporterName || '--'" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报案人电话">
              <el-input :value="currentDetailData.reporterPhone || '--'" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>

</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from "@/router";
import hxxp from '@/utils/hxxp.js'

// 状态管理
const tableLoading = ref(false)
const claimList = ref([])
const total = ref(0)
const totalPages = ref(0)
const errorMsg = ref('')

// 分页参数（与后端默认值一致：pageNum=1，pageSize=2）
const currentPage = ref(1)
const pageSize = ref(2)

// 搜索表单（仅保留报案号查询，参数名与后端一致：reportId）
const searchForm = ref({
  reportId: '' // 后端接口接收的报案号查询参数名
})

// 详情弹窗相关变量
const detailDialogVisible = ref(false)
const currentDetailData = ref({})

// 打开详情弹窗
const openDetailDialog = (row) => {
  currentDetailData.value = { ...row }
  detailDialogVisible.value = true
}

/**
 * 核心：调用后端getDispatch接口获取数据
 * 请求方式：GET
 * 参数：pageNum（分页）、pageSize（分页）、reportId（报案号查询）
 */
const fetchData = async () => {
  try {
    tableLoading.value = true
    errorMsg.value = ''

    // 构造请求参数（与后端接口参数完全匹配）
    const queryParams = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      // 仅当报案号有值时传递，为空时查所有数据
      ...(searchForm.value.reportId && { reportId: searchForm.value.reportId.trim() })
    }

    // 调用目标接口（GET方法，参数通过query传递）
    const res = await hxxp.get('/aiSurveyReport/getDispatch', {
      params: queryParams, // GET请求参数放在params中
      timeout: 10000
    })

    console.log('后端响应数据:', res)
    const response = res || {}

    // 校验后端返回格式（按后端实际结构判断）
    if (response.code !== 100200) {
      throw new Error(`接口错误: ${response.msg || '未知错误'}`)
    }

    // 提取分页和列表数据（后端返回data层包含分页信息）
    const data = response.data || {}
    claimList.value = Array.isArray(data.data) ? data.data : [] // 列表数据
    total.value = Number(data.total) || 0 // 总记录数
    totalPages.value = Number(data.totalPages) || 0 // 总页数
    currentPage.value = Number(data.pageNum) || 1 // 同步后端返回的当前页码

    // ElMessage.success(`数据加载成功，当前第${currentPage.value}页`)

  } catch (error) {
    console.error('请求失败:', error)
    claimList.value = []
    total.value = 0
    totalPages.value = 0

    // 错误分类提示
    if (error.response) {
      errorMsg.value = `请求失败（${error.response.status}）: ${error.response.statusText || '服务器异常'}`
    } else {
      errorMsg.value = error.message || '数据加载失败，请检查网络'
    }

    ElMessage.error(errorMsg.value)
  } finally {
    tableLoading.value = false
  }
}

// 分页变更处理
const handleCurrentPageChange = (page) => {
  currentPage.value = page
  fetchData()
}

const handlePageSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1 // 切换页大小时重置到第一页
  fetchData()
}

// 搜索与重置（搜索参数为reportId）
const handleSearch = () => {
  currentPage.value = 1 // 搜索时重置到第一页
  fetchData()
}

const resetSearch = () => {
  searchForm.value = { reportId: '' } // 仅重置报案号查询
  currentPage.value = 1
  fetchData()
}

// 页面初始化加载数据
onMounted(() => {
  fetchData()
})

/**
 * 辅助方法：查勘状态文本转换（后端返回1-待查勘/2-查勘中/3-已查勘）
 */
const getSurveyStatusText = (status) => {
  const statusMap = {
    1: '待查勘',
    2: '查勘中',
    3: '已查勘',
    null: '--'
  }
  return statusMap[status] || '未知状态'
}

/**
 * 辅助方法：查勘状态标签样式
 */
const getSurveyStatusTagType = (status) => {
  switch (status) {
    case 1: return 'warning' // 待查勘-警告色
    case 2: return 'info'    // 查勘中-信息色
    case 3: return 'success' // 已查勘-成功色
    default: return 'default'
  }
}

/**
 * 辅助方法：时间格式化（适配后端返回的ISO时间格式）
 */
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  if (isNaN(date.getTime())) return dateStr // 时间格式异常时返回原始值

  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')
    }-${String(date.getDate()).padStart(2, '0')
    } ${String(date.getHours()).padStart(2, '0')
    }:${String(date.getMinutes()).padStart(2, '0')
    }:${String(date.getSeconds()).padStart(2, '0')
    }`
}

/**
 * 跳转到处理页（携带报案号参数）
 */
const toHandlePage = (row) => {
  router.push({
    path: '/updateSurvey',
    query: {
      reportNo: row.reportNo,
      surveyWorkNo: row.surveyorWorkNo,
      surveyId: row.surveyId // 传递查勘ID
    }
  })
}
</script>

<style scoped>
.claim-list-page {
  padding: 20px;
  background-color: #ffffff;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eeeeee;
}

.page-header h1 {
  font-size: 20px;
  font-weight: 600;
  color: #333333;
  margin: 0 0 8px;
}

.page-header p {
  font-size: 14px;
  color: #666666;
  margin: 0;
  line-height: 1.5;
}

.search-container {
  margin-bottom: 20px;
}

.btn-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.el-table {
  margin-bottom: 16px;
}

.el-table td,
.el-table th {
  font-size: 13px;
  color: #333333;
  line-height: 1.8;
}

.el-table th {
  background-color: #f8f9fa !important;
}

.location-text {
  font-size: 13px;
  color: #666666;
  cursor: default;
  word-break: break-all;
  white-space: normal;
}

.pagination-container {
  margin-top: 8px;
  display: flex;
  justify-content: flex-end;
  padding-right: 4px;
}

.empty-container {
  margin: 60px auto;
  text-align: center;
  width: 100%;
}

.empty-container .el-button--text {
  margin-top: 16px;
  color: #409eff;
}

/* 响应式适配 */
@media (max-width: 1200px) {
  .search-container .el-col {
    flex: 1 1 auto;
    max-width: 100%;
  }

  .el-table {
    overflow-x: auto;
    width: 100%;
  }
}

@media (max-width: 768px) {
  .claim-list-page {
    padding: 12px 8px;
  }

  .pagination-container {
    justify-content: center;
    padding-right: 0;
  }

  .detail-form .el-form-item {
    margin-bottom: 16px;
  }

  .el-form-item__label {
    font-size: 13px;
    font-weight: 500;
  }
}
</style>